<template>
  <div class="page-wrap">
    <div style="color: rgb(27, 76, 184); margin-bottom: 15px">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnCompanyList"> 实网演练 </span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="cursor: pointer" @click="returnCompany">
        {{ this.$route.query.name }}
      </span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="cursor: pointer" @click="returnAnalysis">数据包分析</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">在线分析</span>
    </div>
    <div
      class="page-content"
      :style="{
        height: contentHei === 'auto' ? contentHei : `${contentHei}px`,
      }"
    >
      <div class="img-header">
        <Button
          style="margin-right: 15px"
          type="primary"
          ghost
          @click="returnAnalysis"
        >
          <Icon type="md-arrow-back" />
          返回
        </Button>
        <div style="font-weight: 700; font-size: 18px">在线分析</div>
      </div>
      <div class="content-wrap">
        <Row>
          <Col span="24">
            <div class="targetHeader">
              <!-- <Button
                type="primary"
                ghost
                shape="circle"
                style="margin-right: 10px"
              >
                <Icon type="ios-cloud-download-outline" size="14" />
                统计
              </Button>
              <Button
                type="primary"
                ghost
                shape="circle"
                style="margin-right: 10px"
              >
                <Icon type="ios-folder-outline" size="14" />
                分析
              </Button>
              <Button
                type="primary"
                ghost
                shape="circle"
                style="margin-right: 10px"
              >
                <Icon type="ios-folder-outline" size="14" />
                对象导出
              </Button> -->

              <!-- 接口暂时无法处理必传值问题，后续处理 -->
              <Dropdown trigger="click" @on-click="downloadItem" v-if="false">
                <Button type="info" shape="circle" style="margin-right: 10px">
                  <!-- <Icon type="ios-folder-outline" size="14" /> -->
                  <Icon type="ios-cloud-download-outline" size="14" />
                  下载数据包
                </Button>
                <template #list>
                  <DropdownMenu>
                    <DropdownItem name="pcap">PCAP</DropdownItem>
                    <DropdownItem name="pcapng">PCAPNG</DropdownItem>
                  </DropdownMenu>
                </template>
              </Dropdown>

              <DatePicker
                v-if="false"
                :editable="false"
                type="datetimerange"
                :value="queryParams.Dates"
                format="yyyy-MM-dd HH:mm"
                placement="bottom-start"
                confirm
                ref="datePicker"
                placeholder="选择日期"
                transfer
                style="width: 249px; margin-right: 15px"
                @on-ok="clickOkBtn"
                @on-clear="clickClearBtn"
                @on-change="changeDates"
              ></DatePicker>
              <Select filterable
                v-if="false"
                style="width: 150px; margin-right: 10px"
                v-model="queryParams.target"
                placeholder="过滤条件"
                filterable
                clearable
                transfer
                @on-change="changeTarget"
              >
                <Option value="IPV4">源IPV4</Option>
              </Select>
              <Checkbox v-model="queryParams.single" @on-change="chageSingle">
                绝对时间
              </Checkbox>
              <Input
                style="width: 150px; margin-right: 10px"
                v-model.trim="queryParams.name"
                placeholder="输入过滤条件"
                clearable
                @on-change="inputName"
              ></Input>
              <Button type="primary" ghost shape="circle">
                <Icon type="md-refresh" size="14" />
                刷新
              </Button>
              <Page
                class="page_center"
                :total="packetTotal"
                show-total
                show-elevator
                @on-page-size-change="getTargetSize"
                :current="queryParams.pageIndex"
                @on-change="getTargetPage"
              >
              </Page>
            </div>
          </Col>
        </Row>
        <div
          class="demo-split"
          :style="{
            height:
              contentHei === 'auto' ? `${500}px` : `${contentHei - 115}px`,
          }"
        >
          <Split v-model="split" mode="vertical" min="200">
            <template #top>
              <Table border :columns="packetCol" :data="packetList"></Table>
            </template>
            <template #bottom>
              <Split v-model="split1" min="200">
                <template #left>
                  <div class="demo-split-pane">
                    <Tree :data="treeData"></Tree>
                  </div>
                </template>
                <template #right>
                  <div class="demo-split-pane">
                    <Button type="info">{{ btnBytes }}</Button>
                    <div class="margin_right_10">
                      <ButtonGroup style="float: right" size="small">
                        <Button
                          :type="btnType == 'hex' ? 'info' : 'default'"
                          @click="clickBtnBytes('hex')"
                          >Hex</Button
                        >
                        <Button
                          :type="btnType == 'bits' ? 'info' : 'default'"
                          @click="clickBtnBytes('bits')"
                          >Bits</Button
                        >
                      </ButtonGroup>
                    </div>
                  </div>
                </template>
              </Split>
            </template>
          </Split>
        </div>
      </div>
    </div>
    <Modal
      :value="progress.show"
      title="下载进度"
      width="500"
      :mask-closable="false"
      footer-hide
      @on-visible-change="change"
    >
      <Progress
        :percent="progress.progress"
        :stroke-width="20"
        :status="progress.status"
        text-inside
      />
    </Modal>
  </div>
</template>
<script>
import PackageProgress from '@/components/package-progress/package-progress.vue';
import { mapState } from 'vuex';
import networkBehavior from '@/view/drill_compete/page/componentHW/networkBehavior'
import threatEvent from '@/view/drill_compete/page/componentHW/threatEvent'
import trafficRetrieval from '@/view/drill_compete/page/componentHW/trafficRetrieval'
import SearchTable from '@/components/SearchTable/SearchTable';
import {fullFlowDown,sessionDetailKey,sessionKeyValue,trafficArchivingDown} from '@/api/integration3d';
export default {
  name:'lineAnalysis',
  components: { PackageProgress,SearchTable},
  data() {

    return {
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      monitorDefault: 'networkBehavior',
      // 裁判禁用行为监控
      showMonitoring: false,
      queryParams: {
        pageIndex: 1,
        pageSize: 12,
        Dates: [],
        endTime: '', //结束时间 ,
        startTime: '',//开始时间
        target: '',
        single: false,
        sessionQueryConditionList: [],
        projectId: "J6c710a699fd4d83a7418c468bf5b562",
      },
      packetTotal: 0,
      packetList: [{ time: '123', source: '123', destination: '123', protocol: '123', length: '123', info: '123' }, { time: '123', source: '123', destination: '123', protocol: '123', length: '123', info: '123' }],
      packetCol: [
        {
          // title: 'No.',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: 'Time',
          key: 'time',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          width: 260,
          // resizable:true
        },
        {
          title: 'Source',
          key: 'source',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140,
          placement: 'top-left'
        },
        {
          title: 'Destination',
          key: 'destination',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140,
          // resizable:true
        },
        {
          title: 'Protocol',
          key: 'protocol',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140,
          // resizable:true
        },
        {
          title: 'Length',
          key: 'length',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 140,
          // resizable:true
        },
        {
          title: 'Info',
          key: 'info',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          // minWidth: 200,
          // resizable: true,

        },
      ],

      // 树型数据
      treeData: [
        {
          title: 'IPV4',
          expand: true,
          children: [
            {
              title: 'IPV4 1-1-1'
            },
            {
              title: 'IPV4 1-1-2'
            }
          ]
        },
        {
          title: 'IPV6',
          expand: true,
          children: [
            {
              title: 'IPV6 1-1-1'
            },
            {
              title: 'IPV6 1-1-2'
            }
          ]
        },
        {
          title: 'port',
          expand: true,
          children: [
            {
              title: 'port 1-1-1'
            },
            {
              title: 'port 1-1-2'
            }
          ]
        }
      ],
      handleRecordsModal: true,
      split: 0.3,
      split1: 0.5,
      btnBytes: 'Frame (331 bytes)',
      btnType: 'hex',
      progress: {
        show: false,
        progress: 0,
        status: 'active'
      },
    }
  },
  computed: {
    ...mapState('board', ['newNotice'])
  },
  watch: {},
  created() {},
  async mounted() {
    this.setStyle();
    window.onresize = () => {
      this.setStyle();
    };
  },
  methods: {
    // 点击二进制切换按钮颜色
    clickBtnBytes (val) {
      if (val == 'hex') {
        
      }
      this.btnType =val
    },

    // 拖拽中
    onMoving (e) {
      console.log('8 ~ onMoving ~ e:', e)
      return
      
    },

    getTargetPage (val) {
      this.queryParams.pageIndex = val
    },
    getTargetSize (size) {
       this.queryParams.pageSize = size;
    },

    // 选择时间
    clickOkBtn () {
      // this.getFlowMachlake()
    },
    clickClearBtn () {
      // this.queryParams.Dates = []
      this.changeDates()
      this.clickOkBtn()
    },
    changeDates (timeList) {
      console.log('hangeDates ~ timeList:', timeList)
      if (timeList && timeList[0]) {
        this.queryParams.Dates = timeList
        this.queryParams.startTime = timeList[0]
        this.queryParams.endTime = timeList[1]
      } else {
        this.queryParams.Dates = []
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },

    // 单选框
    chageSingle (val) {
      console.log('chageSingle ~ val:', val)
    },

    // 条件
    changeTarget (val) {
      console.log('changeTarget ~ val:', val)
    },

    // 过滤条件
    inputName () {
      console.log('==========inputName',this.queryParams);
    },
    

    //在线分析
    toLineAnalysis () {
      console.log('=====点击分析');
       this.$router.push({
        path: '/lineAnalysis',
        query: {
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page
        }
      });
    },

    // 导出
    downloadItem (val) {
      console.log('🚀 ~ file: trafficRetrieval.vue:479 ~ downloadItem ~ val:', val)
      let project = this.$route.query.prjid
      // let project = 'Jaffae2f077b417eb359a3ebda67dd37'。
      let data = {
        endTime: this.queryParams.endTime,
        startTime: this.queryParams.startTime,
        fileName: '', // 文件名称
        fileType: val,
        projectId: project,
        offlineTaskId: "",
        queryCondition: this.queryParams.sessionQueryConditionList,
      }
      if (data.queryCondition.length == 0) {
        delete data.queryCondition
      }
      trafficArchivingDown(data).then(res => {
        if (res.code == 1) {
          console.log('=========', res.data);
          this.downloadDrillReport(res.data, val)
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    downloadDrillReport (taskId, val) {
      let sceneId = this.$route.query.id;
      this.progress.show = true
      let flag = false // 不存在文件，进度条控制为0
      fullFlowDown(taskId, this.downFileProgress).then(res => {
        this.totalProgress = 0
        if (res.type == 'application/octet-stream') {
          const link = document.createElement("a");
          const href = window.URL.createObjectURL(res);
          link.href = href;
          link.download = `${this.$route.query.name}-数据包.${val}`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        } else {
          flag = true
          this.progress.status = 'wrong'
          this.$Message.error('下载文件失败!不存在文件数据！');
        }
      }).catch(error => {
        this.progress.status = 'wrong'
        this.$Message.error('下载失败!');
      }).finally(() => {
        if (flag) {
          this.progress.progress = 0
        } else {
          this.progress.progress = 100
        }
        setTimeout(() => {
          this.progress.show = false
          this.progress.status = 'active'
          this.progress.progress = 0
        }, 2000)

      })
    },
    // 进度
    downFileProgress (progress) {
      let currentProgress = progress.loaded * 1; //B单位
      if (this.totalProgress) {
        this.totalProgress += currentProgress
      } else {
        this.totalProgress = currentProgress
      }
      currentProgress = this.totalProgress - currentProgress ? currentProgress : currentProgress / 2;
      let rate = (((this.totalProgress - currentProgress) / this.totalProgress) * 100).toFixed(2) * 1;
      if (!this.rate || rate > this.rate) {
        this.progress.progress = rate;
      }
    },

     change (val) {
      this.progress.show = val
    },



    // 设置高度
    setStyle() {
      clearTimeout(this.refreshTimer);
      this.refreshTimer = setTimeout(() => {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        this.fullHeight = window.fullHeight;
        this.fullWidth = window.fullWidth;
        this.contentHei = this.fullHeight - 36 - 50; // 80是头部高度  60是上下padding
        this.pageSize = Math.floor((this.contentHei - 167) / 96) || 1;
        // this.getReportList();
      }, 200);
    },

    // 返回数据包详情
    returnAnalysis () {
      this.$router.push({
        path: '/packetAnalysis',
        query: {
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page
        }
      });
    },

    // 返回详情
    returnCompany () {
      this.$router.push({
        path: '/hwDrillDetail',
        query: {
          name: this.$route.query.name,
          prjid: this.$route.query.prjid,
          id: this.$route.query.id,
          page: this.$route.query.page
        }
      });
    },

    // 返回列表
    returnCompanyList () {
      this.$router.push({
        path: '/hwDrill'
      });
    }
  }
};
</script>
<style scoped>
.demo-split {
  min-height: 200px;
  border: 1px solid #dcdee2;
  border-radius: 10px;
  overflow: hidden;
}
.demo-split-pane {
  /* padding: 10px; */
  min-height: 200px;
  margin: 15px 0px 0px 10px;
}
.content-wrap .ivu-split-pane.bottom-pane {
  bottom: 0;
  background: #dcdee2;
}
.page_center {
  /* margin-top: 15px; */
  /* text-align: end; */
  margin-left: 10px;
}
.targetHeader {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
  margin: 15px 0px;
}
.targetHeader_left {
  margin: 15px 0px 0px 10px;
  /* border-right: 1px solid #999; */
  /* height: calc(100vh - 13vh); */
}

.margin_right_10 {
  margin-right: 10px;
}
.page-wrap {
  padding: 25px;
}
.page-wrap-query /deep/ .ivu-cascader-rel .ivu-input {
  border-radius: 20px;
}
.reset-color /deep/ .ivu-select-selected-value {
  color: unset !important;
}
.page-content {
  background-color: #fff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}
.img-header {
  display: flex;
  /* justify-content: space-between; */
  padding: 20px 20px 0 20px;
  justify-content: flex-start;
  align-items: center;
}
.addressIcon {
  display: inline-block;
  height: 14px;
  width: 12px;
  background: url("../../../../assets/globalIcon/addressIcon.png") no-repeat
    center;
  background-size: 100% 100%;
  margin-bottom: -1px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.content-wrap {
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 20px;
  flex: 1;
  height: 0;
}
.content-wrap::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
}
.content-wrap::-webkit-scrollbar-thumb {
  /*滚动条里面小方块样式*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(209, 209, 209, 0.6);
}
.content-wrap::-webkit-scrollbar-track {
  /*滚动条里面轨道样式*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  background: rgba(179, 179, 179, 0.1);
}
</style>
